package com.lzz.bottomencapsulation.net;

import android.content.Context;
import android.text.TextUtils;

import com.lzz.bottomencapsulation.consts.NetConsts;
import com.lzz.bottomencapsulation.utils.AppUtils;
import com.lzz.bottomencapsulation.utils.LUtils;
import com.lzz.bottomencapsulation.utils.SPUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 网络请求封装
 */
public class RetrofitBase {
    private static RetrofitBase retrofitBase;
    private static Retrofit retrofit;

    /**
     * 创建单例
     */
    public static RetrofitBase getInstace(final Context context) {
        if (retrofitBase == null) {
            synchronized (RetrofitBase.class) {
                retrofitBase = new RetrofitBase(context);
            }
        }
        return retrofitBase;
    }

    OkHttpClient okHttpClient;

    private RetrofitBase(final Context context) {
        if (null == retrofit) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.interceptors().add(AddRequestHeader(context));
            openDebugLog(builder);
            builder.connectTimeout(NetConsts.CONNECT_TIMEOU, TimeUnit.SECONDS);
            okHttpClient = builder.build();

        }
    }

    public Retrofit setBaseUrl(String baseUrl) {
        return retrofit = new Retrofit.Builder().client(okHttpClient).addCallAdapterFactory
                (RxJavaCallAdapterFactory.create())//添加rxjava
                .addConverterFactory(GsonConverterFactory//添加GSon转化
                        .create()).baseUrl(baseUrl)//ip
                .build();
    }


    /**
     * 开关debug  打印日志
     *
     * @param builder
     */
    private void openDebugLog(OkHttpClient.Builder builder) {
        if (NetConsts.isDebug) {
//              打印日志
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

                @Override
                public void log(String message) {
                    LUtils.e("网络请求", message);
                }
            });
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);//设置打印日志
            builder.addInterceptor(httpLoggingInterceptor);
        }
    }

    /***
     * 添加请求头
     */
    private Interceptor AddRequestHeader(final Context context) {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder().addHeader("version",
                        AppUtils.getVersionName(context)).addHeader("device", AppUtils
                        .getIphoneDeviceid(context)).addHeader("systemVersion", android.os.Build
                        .VERSION.SDK_INT + "").addHeader("system", "A").addHeader("phoneBrand",
                        android.os.Build.BRAND + "").addHeader("phoneModel", android.os.Build
                        .MODEL + "");
                String umengToken = (String) SPUtils.get(context, "umengToken", "");
                if (!TextUtils.isEmpty(umengToken)) {
                    requestBuilder.addHeader("umengToken", umengToken);
                }
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };
    }

    /**
     * 网络请求
     *
     * @param context
     * @param observable
     * @param callBack
     * @param <T>
     * @return
     */
    public static <T> Subscription setSubscribeOn3(Context context,
                                                   Observable<HttpRequestData<T>> observable,
                                                   RequestCallBack<T> callBack) {
        return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                subscribe(new SubscriberOne<>(callBack, context));
    }

}
